//
//  ShareViewController.m
//
//  Copyright 2012 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#import "ResultsViewController.h"

#import "GTLShopping.h"
#import "ShareViewController.h"

@implementation ResultsViewController

@synthesize products = _products;

// Handle the ResultsViewController's segues.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  // Make sure your segue name in storyboard is the same as this line
  if ([[segue identifier] isEqualToString:@"ShareSegue"]) {
    
    // Get the cell that was pressed.
    NSIndexPath *path = [self.tableView indexPathForSelectedRow];
    
    // Fetch the product at that index.
    GTLShoppingProduct *product = [_products itemAtIndex:[path row]];
    
    // Set up the view controller.
    ShareViewController *vc = [segue destinationViewController];
    
    // Pass only what we need to the view controller.
    [vc initUI:product.product.title
     withBrand:product.product.brand
        andURL:product.product.link];
  }
}

// Set up the source of the table from the previous view.
- (void)setDataSource:(id)data {
  _products = data;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section {
  NSArray *items = self.products.items;
  return items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  GTLShoppingProduct *item = [self.products itemAtIndex:indexPath.row];
  
  // Use the title of the product for the cell.
  UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:@"ProductCell"];
  cell.textLabel.text = item.product.title;
  return cell;
}

#pragma mark - Table view delegate

// When the user presses a product, start the segue.
- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [self performSegueWithIdentifier:@"ShareSegue" sender:nil];
}

@end
